package im.oen.boot.common.utils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Kevin.Xu
 */
public class RegexUtil {

    private static final String REGEX_EMAIL = "[a-zA-Z_]{0,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z]{1,}";
    private static final String REGEX_PHONE = "^[1][3,4,5,6,7,8,9][0-9]{9}$";
    private static final String REGEX_URL = "^http[s]{0,1}://([\\w.]+\\/?)\\S*";

    public static boolean match(String regEx, String str) {
        Matcher matcher = matcher(regEx, str);
        return matcher.matches();
    }

    public static Matcher matcher(String regEx, String str) {
        Pattern pattern = Pattern.compile(regEx);
        return pattern.matcher(str);
    }

    public static List<String> fetch(String regEx, String source) {
        Matcher matcher = RegexUtil.matcher(regEx, source);
        if (!matcher.find()) {
            return null;
        }
        int count = matcher.groupCount();
        List<String> list = new ArraySet<>();
        for (int i = 0; i < count; i++) {
            list.add(matcher.group(i));
        }
        return list;
    }

    public static int indexOf(String regEx, String str) {
        if (Checker.hasEmpty(str, regEx)) {
            return -1;
        }
        Matcher matcher = matcher(regEx, str);
        if (matcher.find()) {
            return matcher.start();
        }
        return -1;
    }

    public static String fetchFirst(String regEx, String source) {
        Matcher matcher = RegexUtil.matcher(regEx, source);
        if (!matcher.find()) {
            return null;
        }
        return matcher.group();
    }

    public static boolean isEmail(String str) {
        if (Checker.isEmpty(str)) {
            return false;
        }
        return RegexUtil.match(REGEX_EMAIL, str);
    }

    public static boolean isPhone(String str) {
        if (Checker.isEmpty(str)) {
            return false;
        }
        return RegexUtil.match(REGEX_PHONE, str);
    }

    public static boolean isUrl(String str) {
        if (Checker.isEmpty(str)) {
            return false;
        }
        return RegexUtil.match(REGEX_URL, str);
    }
}
